<template>
<div>
  <el-card class="search-card">
    <BasicForm
      :formItemWidth="'90px'"
      ref="formData"
      :formColumns="formItemList"
      :dataSource="formData"
      :defaultExpandStatus="false"
      :handleSearchForm="handleQueryForm"
      :colNumOfRow="3"
      @getFormData="getFormData"
    ></BasicForm>
  </el-card>
  <el-card class="table-card">
    <basic-table
      showActionCol
      :showSelectCol="false"
      :loading="tableInfo.loading"
      :columns="tableInfo.columns"
      :dataSource="tableInfo.list"
      :pagination="pagination"
      :tableHeight="445"
      :actionColWidth="150"
      :actionRender="renderTableBtnAction"
      @pageChange="handlePageChange"
      @pageSizeChange="handlePageSizeChange"
    >
      <el-row slot="content_context" type="flex" justify="start">
        <BtnRender :render="renderBtnsBar" />
      </el-row>
    </basic-table>
  </el-card>
</div>
</template>
<script>
import BasicPage from '@/mixins/supplier/basicPage';
import BasicForm from '@/components/supplier/BasicForm';
import BasicTable from '@/components/supplier/BasicTable';
import { FORM_ITEM_LIST, TABLE_COLUMNS } from './constants';
import { getBtnsBar, getTableAction } from '@supplier/utils/btnsUtils';
import BtnRender from '@/components/JSXRender/BtnRender';
import { createExcelByExport, setAuthBtnId } from '@/utils/bizUtils';
import {
  queryCheckPlanListService,
  exportCheckPlanService,
  deletePlanService,
} from '@/api/supplier/supervision/checkPlan'
import {
  getWorkflowJumpUrl,
  retrieveWorkflow,
} from '@/api/supplier/workflow';

export default {
  mixins: [BasicPage],
  components: {
    BasicForm,
    BasicTable,
    BtnRender
  },
  data () {
    return {
      formItemList: FORM_ITEM_LIST,
      formData: {
        planCode: '',
        planName: '',
        startYear: '',
        endYear: '',
        status: '',
        createUser: '',
        doTime: []
      },
      tableInfo: {
        list: [],
        columns: TABLE_COLUMNS,
        loading: false,
        selection: []
      }
    }
  },
  computed: {
    // 表单入参
    formParams () {
      const [startTime = '', endTime = ''] = this.formData['doTime'];
      let params = {
        ...this.formData,
        startTime,
        endTime,
      };
      delete params.doTime;
      return params;
    }
  },
  mounted () {
    this.handleQueryForm();
  },
  methods: {
    // 渲染按钮操作栏
    renderBtnsBar (h) {
      const btnsBar = [
        {
          label: '新建核查计划',
          authLabel: '新增',
          method: this.handleAddPlan,
          size: 'mini',
          type: 'primary',
          hasAuth: true
        }
      ];
      if (this.supplierExportConfig.supervision) {
        btnsBar.unshift({
          label: '导出',
          method: this.handleExport,
          loading: this.exportLoading,
          size: 'mini',
          type: 'primary',
          hasAuth: true
        })
      }
      return getBtnsBar(h, btnsBar, this.showBtn);
    },
    // 1：暂存 10：待审核，20：审核通过，30：审核驳回, 40: 撤回
    renderTableBtnAction (h, { row }) {
      const actionBtnList = [
        { label: '查看', method: () => { this.handleView({ row, type: 'view' }) }, },
        { label: '编辑', method: this.handleEdit, hasAuth: true, status: [1, 30, 40] },
        { label: '删除', method: this.handleDelete, hasAuth: true, status: [1, 30, 40] },
        { label: '审批流', method: this.handleAudit, hasAuth: true, status: [10, 20, 30] },
        { label: '取回', method: this.handleWithdraw, hasAuth: true, status: [10] },
        { label: '修改核查方式', authLabel: '编辑', method: () => { this.handleView({ row, type: 'edit' }) }, hasAuth: true, status: [20] }
      ];
      const actionList = actionBtnList.filter(item => !item.status || item.status.includes(row.status))
      return getTableAction({ h, row, actionList, showBtn: this.showBtn });
    },
    // 取回单据
    handleWithdraw (row) {
      this.$confirm('确定要取回当前计划吗?', '取回', {
        type: 'warning'
      }).then(() => {
        this.handleCancel(row)
      }).catch(() => {});
    },
    async handleCancel (row) {
      const res = await retrieveWorkflow(
        { oaRequestId: row.requestId },
        state => { this.tableInfo.loading = state }
      )
      if (res) {
        this.$message.success('取回成功')
        this.getTableData()
      }
    },
    // 审批流
    async handleAudit (row) {
      const res = await getWorkflowJumpUrl(
        { requestId: row.requestId },
        state => { this.tableInfo.loading = state }
      )
      if (res?.result) {
        window.open(res.result, '_blank')
      }
    },
    // 新建计划
    handleAddPlan () {
      this.$router.push({ name: 'addCheckPlan' })
    },
    // 编辑
    handleEdit (row) {
      const { id } = row;
      this.$router.push({ name: 'addCheckPlan', query: { id } })
    },
    // 查看
    handleView ({ row, type }) {
      const { id } = row;
      this.$router.push({ name: 'viewCheckPlan', query: { planId: id, type } })
    },
    // 删除
    handleDelete (row) {
      this.$confirm('此操作将永久删除该计划, 是否继续?', '提示', {
        type: 'warning'
      }).then(() => {
        this.deletePlanAction(row)
      }).catch(() => {});
    },
    // 删除计划
    async deletePlanAction (row) {
      const res = await deletePlanService(
        { planId: row.id },
        state => { this.tableInfo.loading = state }
      )
      if (res) {
        this.$message.success('删除成功')
        this.getTableData()
      }
    },
    // 获取表单查询入参
    getParamsBySearchForm () {
      const { current, size } = this.pagination;
      return { ...this.formParams, current, size };
    },
    // 获取表格数据
    async getTableData () {
      setAuthBtnId();
      const res = await queryCheckPlanListService(
        this.getParamsBySearchForm(),
        state => { this.tableInfo.loading = state }
      );
      if (res?.result) {
        this.tableInfo.list = res.result?.records || [];
        this.pagination.total = res.result.total;
      }
    },
    // 导出
    async handleExport () {
      const res = await exportCheckPlanService(this.formParams, state => { this.exportLoading = state });
      if (res) {
        createExcelByExport({ res, excelTitle: '核查计划列表' });
      }
    },
  }
}
</script>
